package com.yeb.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.yeb.server.pojo.*;
import com.yeb.server.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shi
 * @since 2022-05-06
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService iEmployeeService;

    @Autowired
    private IPoliticsStatusService iPoliticsStatusService;

    @Autowired
    private IJoblevelService iJoblevelService;

    @Autowired
    private INationService iNationService;

    @Autowired
    private IDepartmentService iDepartmentService;

    @Autowired
    private IPositionService iPositionService;

    @ApiOperation(value = "获取所有员工(分页)")
    @GetMapping("/")
    public RespPageBean getEmployee(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer size,
            Employee employee, LocalDate[] beginDateScope){
        return iEmployeeService.getEmployeeByPage(currentPage,size,employee,beginDateScope);

    }
    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return iPoliticsStatusService.list();
    }
    @ApiOperation("获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJoblevels(){
        return iJoblevelService.list();
    }
    @ApiOperation("获取所有名族")
    @GetMapping("/nations")
    public List<Nation> getAllNations(){
        return iNationService.list();
    }
    @ApiOperation("获取所有部门")
    @GetMapping("/departments")
    public List<Department> getAllDepartments(){
        return iDepartmentService.getAllDepartment();
    }
    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPosition(){
        return iPositionService.list();
    }
    @ApiOperation("获取工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID(){
        return iEmployeeService.maxWorkID();
    }
    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee){
        return iEmployeeService.addEmp(employee);
    }
    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee){
        if (iEmployeeService.updateById(employee)){
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }
    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable Integer id){
        if (iEmployeeService.removeById(id)){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }
    @ApiOperation(value = "导出员工到excel")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        List<Employee> employees = iEmployeeService.getEmployee(null);
        ExportParams params=new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook sheets = ExcelExportUtil.exportExcel(params, Employee.class, employees);
        ServletOutputStream out=null;
        try {
            response.setHeader("content-type","application/vnd.ms-excel");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
           out = response.getOutputStream();
           sheets.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null!=out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public RespBean importEmp(MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nationList = iNationService.list();
        List<PoliticsStatus> politicsStatusList = iPoliticsStatusService.list();
        List<Department> departmentList = iDepartmentService.list();
        List<Joblevel> joblevelList = iJoblevelService.list();
        List<Position> positionList = iPositionService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            list.forEach(employee -> {
                /**Nation nation = new Nation(employee.getNation().getName());
                int i = nationList.indexOf(nation);
                nationList.get(i);**/
                //用name得到实体类然后获取对应id进行设置
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
            });
            if (iEmployeeService.saveBatch(list)){
                return RespBean.success("导入成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败！");
    }
}
